/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.edu.iuh.dhth7dlt.emailclient.utils;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Scanner;

/**
 *
 * @author Friendless
 */
public final class POP {

    private TCP tcp;
    private String server;
    private int port;
    private String user;    
    private String pass;
    private String pathDB;
    private String response;
    private String code;
    private boolean isSaveEmailOnServer;
    private boolean isOK = true;

    public POP(HashMap<String, String> params) throws IOException, EmailExceptions {
        server = params.get("PopServer");
        port = Integer.parseInt(params.get("port"));
        user = params.get("user");
        pass = params.get("pass");
        pathDB = params.get("pathDB");
        isSaveEmailOnServer=Boolean.parseBoolean(params.get("isSaveEmail"));


        //Khởi tạo socket
        tcp = new TCP(server,port);

        //Đăng nhập
        response = tcp.request("USER " + user);
        code = split_response(response)[0];
        if (!code.startsWith("+OK")) {
            isOK=false;
            throw new EmailExceptions().set_error("Lỗi username");
        }

        response = tcp.request("PASS " + pass);
        code = split_response(response)[0];
        if (!code.startsWith("+OK")) {
            isOK=false;
            throw new EmailExceptions().set_error("Lỗi Password");
        }
    }

   

    public void getUpdateEmail() throws EmailExceptions, SQLException, ClassNotFoundException, IOException {
        //Lấy danh sách email        
        String[] listEmailID = getListIDEmail();
        if (listEmailID == null) {
            return;
        }
        for (int i = 0; i < listEmailID.length; i++) {
            while (!(response = tcp.request("RETR " + listEmailID[i])).startsWith("+OK"));
            //Xóa Email trên server nếu không chọn lưu email trên server
            code = split_response(response)[0];
            if (!code.startsWith("+OK")) {
                throw new EmailExceptions().set_error("Lỗi không tải được email");
            }

            //Lưu vào CSDL
            SqliteHelper helper = new SqliteHelper(pathDB);
            String dataEmail=tcp.getNextResponse().replaceAll("[\r\n.]+$", "");
            helper.insertEmail(listEmailID[i],dataEmail);
            if(!isSaveEmailOnServer)
                delelteEmailByID(listEmailID[i]);
        }
        //Cập nhật lại email nếu xóa.
        close();


    }

    private String[] getListIDEmail() throws EmailExceptions, IOException {
        //Lấy list danh sách email
        response = tcp.request("LIST");
        code = split_response(response)[0];
        if (!code.startsWith("+OK")) {
            throw new EmailExceptions().set_error("Lỗi Lấy danh sách email");
        }
        String result = "";
        if (!"0".equals(split_response(response)[1])) {
            Scanner s = new Scanner(response);
            String line = "";
            while (s.hasNextLine()) {
                line = s.nextLine();
                if (line != null && line.length() > 0) {
                    if (line.charAt(0) == '.') {
                        break;
                    }
                    if (line.charAt(0) == '+') {
                        continue;
                    }
                    result += new StringBuffer().append(line.split(" ")[0]).append(",");
                }
            }
        }
        
        return result.length() == 0 ? null : result.split(",");
    }

    String[] split_response(String response) {
        return response.split(" ");
    }

    //Xóa thư theo ID
    public void delelteEmailByID(String id) throws EmailExceptions, IOException {
        response = tcp.request("dele " + id);
        if(response.startsWith("-ERR No such message")) {
            return;
        }
        code = split_response(response)[0];
        if (!code.startsWith("+OK")) {
            throw new EmailExceptions().set_error("Lỗi không xóa được email trên server");
        }
       
    }
    public boolean isConfigOK()
    {
        return isOK;
    }
    public void close() throws IOException, EmailExceptions
    {
        response = tcp.request("quit");
        code = split_response(response)[0];
        if (!code.startsWith("+OK")) {
            throw new EmailExceptions().set_error("Lỗi thoát");
        }
    }
}
